trigger TriggerReturnOrderApproval on Order__c (after update)
{
    List<Account> accList=new List<Account>();
   
    String sql='select Id,name from Account where Id in ';
    String filter='';
    
    for(Order__c ord:Trigger.new)
    {
        if(filter.length()>0)
        {
            filter+=',';
        }
        
        if(ord.Outlet_name__c == null)
        {
            ord.addError('订单没有关联的门店！');
        }
        else
        {
            filter+='\''+ord.Outlet_name__c+'\'';
        }
    }
    if(filter.length()>0)
    {
        sql+='('+filter+')';
    }
    else
    {
        return;
    }
    
    accList=DataBase.query(sql);
    
     for(Integer i = 0; i < trigger.new.size(); i++)
     {
        // 在Item被写完时
        if(trigger.new[i].ItemsDone__c && !trigger.old[i].ItemsDone__c)
        {
            // 退货和免费产品订单被提交审批
            if(trigger.new[i].OrderType__c=='退货' || trigger.new[i].OrderType__c=='免费产品' || trigger.new[i].OrderType__c=='活动订单')
            {
                if(!trigger.new[i].Approval__c)
                {
                    SendOrder.SendOrderToApproval(trigger.new[i]);
                }
            }
            else // 普通产品订单提交给经销商，并同时发消息给TSR
            {
                if(trigger.new[i].SendOrderToDistributor__c)//判断是否要发送给经销商
                {
                    SendOrder.SendOrderToDistributor(trigger.new[i].Id);
                    SendMessage(i,1);
                }
            }
        }
        // 审批通过时
        else if (trigger.new[i].Approval__c && !trigger.old[i].Approval__c)
        {
            // 退货和免费产品订单提交给经销商，并同时发消息给TSR
            if(trigger.new[i].OrderType__c=='退货' || trigger.new[i].OrderType__c=='免费产品' || trigger.new[i].OrderType__c=='活动订单')
            {
                if(trigger.new[i].SendOrderToDistributor__c)//判断是否要发送给经销商
                {
                    SendOrder.SendOrderToDistributor(trigger.new[i].Id);
                    SendMessage(i,1);
                }
            }
        }
        else if(trigger.new[i].RejectApproval__c && !trigger.old[i].RejectApproval__c)//拒绝审批
        {
            string orderId;
            if(trigger.new[i].OrderType__c=='活动订单')
            {
                orderId=trigger.new[i].id;
                
                    //查找相应的订单列表
                    set<string> resourceIdList=new set<string>();
                    List<Order_Item__c> oItemList=[select id,
                                                                        Product_Name__c,
                                                                        OrderNumber__c,
                                                                        Resource_Allocation_Detail__c 
                                                                        from Order_Item__c 
                                                                        where Order_Name__c=:orderId];
                    for(Order_Item__c oItem:oItemList)
                    {
                        resourceIdList.add(oItem.Resource_Allocation_Detail__c);
                   //     productIdList.put(oItem.Product_Name__c,(Integer)oItem.OrderNumber__c);
                    }
                    //查找相应的用户的分配信息
                    map<id,Resource_Allocation_Detail__c> resList=new map<id,Resource_Allocation_Detail__c>([select id,ProductId__c,
                                                                                                                                                                    Resource_Quantity_Number__c, 
                                                                                                                                                                    HasUsedResourceNumber__c
                                                                                                                                                                    from Resource_Allocation_Detail__c 
                                                                                                                                                                    where id in:resourceIdList]);
                      for(Order_Item__c oItem:oItemList)
                      {
                          if(resList.containsKey(oItem.Resource_Allocation_Detail__c))
                          {
                               Resource_Allocation_Detail__c rad=resList.get(oItem.Resource_Allocation_Detail__c);
                               if(rad.HasUsedResourceNumber__c==NULL)
                                   rad.HasUsedResourceNumber__c=0;
                                   
                             rad.HasUsedResourceNumber__c-=oItem.OrderNumber__c;  
                             /*  if(rad.HasUsedResourceNumber__c<=rad.Resource_Quantity_Number__c)//没有超出10%可以直接减去已使用量
                               {
                                   rad.HasUsedResourceNumber__c-=oItem.OrderNumber__c;
                               }
                               if(rad.HasUsedResourceNumber__c>rad.Resource_Quantity_Number__c)//如果已使用数超出了
                               {
                                   integer num=Integer.valueOf(rad.HasUsedResourceNumber__c)-Integer.valueOf(rad.Resource_Quantity_Number__c);//获得超出的数
                                   rad.HasUsedResourceNumber__c-=oItem.OrderNumber__c-num;//下单数减去超出数
                               }*/
                               resList.put(oItem.Resource_Allocation_Detail__c,rad);
                          }
                      } 
                    update resList.values();
            }
            SendMessage(i,0); 
        }
     } 
     
     private void SendMessage(Integer triggerIndex,Integer typeI)//0:拒绝订单，1:通过订单
     {
        Map<Id,Sobject[]> msgMap=new Map<Id,Sobject[]>();
        //Account acc=[select Name from Account where Id=:trigger.new[triggerIndex].Outlet_name__c];
        for(Account acc:accList)
        {
            if(trigger.new[triggerIndex].Outlet_name__c==acc.Id)
            {
                DateTime dtime=trigger.new[triggerIndex].CreatedDate;
                String dtStr=dtime.format();
            
                Message__c msg=new Message__c(); 
                if(typeI!=0)
                    msg.Name='订单已提交成功，编号为：'+trigger.new[triggerIndex].Name;     
                else
                    msg.Name='订单已被拒绝，编号为：'+trigger.new[triggerIndex].Name;              
                msg.Type__c='营业信息';
                if(typeI!=0)
                {                
                    msg.Content__c='您在'+dtStr+ '日提交的订单已发送到经销商，订单编号：' 
                        + trigger.new[triggerIndex].Name + '，订单类型：' + trigger.new[triggerIndex].OrderType__c 
                        + ',所属门店：'+acc.Name;        
                }      
                else
                {
                    msg.Content__c='您在'+dtStr+ '日提交的订单已被拒绝，订单编号：' 
                        + trigger.new[triggerIndex].Name + '，订单类型：' + trigger.new[triggerIndex].OrderType__c 
                        + ',所属门店：'+acc.Name; 
                }  
                msg.StartDate__c = System.today();
                msg.EndDate__c = System.today().addDays(2);
                //insert msg; 
               // msgList.add(msg);
                
                //Message__c m=[select Id,OwnerId from Message__c where Name=:msg.Name order by CreatedDate desc limit 1];               
                MessageRecipient__c rec=new MessageRecipient__c();                
                rec.Recipient__c=trigger.new[triggerIndex].OwnerId__c;                
               // rec.Message__c=msg.Id;                
                //insert rec;
                sobject[] obj=new sobject[2];
                obj[0]=msg;
                obj[1]=rec;
                msgMap.put(acc.Id,obj);
            }
        }
        List<Message__c> msgList=new List<Message__c>();
        List<MessageRecipient__c> recipientList=new List<MessageRecipient__c>();
        for(Integer i=0;i<accList.size();i++)
        {
            Account acc=accList[i];
            sObject[] obj=msgMap.get(acc.Id);
            if(obj!=NULL)
            {
                msgList.add((Message__c)obj[0]);
                recipientList.add((MessageRecipient__c)obj[1]);
            }
        }
        insert msgList;
        
        for(Integer i=0;i<msgList.size();i++)
        {
            Message__c msg=msgList[i];
            MessageRecipient__c mr=recipientList[i];
            mr.Message__c=msg.Id;
        }
        insert recipientList;
     }
}